<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/17
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\facade\JobOptions;
use app\common\facade\TransItem;
use app\common\services\JobOptionService;
use app\common\services\JobService;
use think\App;
use think\Db;

/**
 * 用户参加的兼职/ 发布的兼职管理
 *
 * Class UserJobs
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/11/17
 */
class UserJobs extends ApiBase
{

    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }




    /**
     * 我参加的兼职列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function joinJobList()
    {
        $applyStatus = $this->request->param('type', 0);
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 8);

        $applyDb = Db::name('jobs_apply')->alias('ja')
            ->where('ja.user_id', $this->userId);

        if ($applyStatus) {
            $applyDb->where('ja.status', $applyStatus);
        }

        $jobList = $applyDb->join('jobs j', 'ja.job_id = j.id')
            ->join('jobs_type jt', 'j.work_type = jt.id')
            ->order('ja.updated_at DESC')
            ->page($page, $pageSize)
            ->field('ja.id as applyId,ja.status as applyStatus,ja.created_at as applyTime')
            ->field('j.*')
            ->field('jt.name as jobTypeName, jt.img as jobTypeImg')
            ->select();

        foreach ($jobList as &$item) {
            $item['applyStatusCh'] = TransItem::transJobApply(Arr::get($item, 'applyStatus'));
            $item['salary_unitCh'] = TransItem::transMoneyUnit(Arr::get($item, 'salary_unit'));
        }

        $this->response($jobList);
    }


    /**
     * 我发布的兼职
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function publishJobList()
    {
        $type = $this->request->param('type', -1);
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 8);
        $where = [
            'page'              => $page,
            'pageSize'          => $pageSize,
            'publishUserId'     => $this->userId,
            'status'            => $type,
            'is_center'         =>1
        ];
        $jobList = (new JobService())->jobList($where, $page, $pageSize);
        foreach ($jobList as &$item) {
            //是否可以结束招聘
            $item['isCloseApply'] = JobOptions::isCloseApply($item);
            $item['isDone'] = JobOptions::isJobDone($item);
            $item['isTop']  = JobOptions::isTop($item);
        }

        $this->response($jobList);
    }


    /**
     * 报名兼职人员列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function applyUserList()
    {
        $jobId = $this->request->param('jobId', 0);
        if ($jobId) {
            $applyList = Db::name('jobs_apply')->alias('ja')
                ->where('ja.job_id', $jobId)
                ->join('jobs j', 'j.id = ja.job_id')
                ->where('j.user_id', $this->userId)
                ->where('j.is_deleted', 0)
                ->where('j.status', 'IN', [2, 4])
                ->join('user u', 'u.id = ja.user_id')
                ->join('user_extend ue', 'ue.user_id = ja.user_id')
                ->field('ja.*, u.truename,u.wechat_nickname,u.avatar')
                ->field('ue.true_sex,ue.true_age,ue.credit_score,ue.join_job_num,ue.mobile as userMobile')
                ->select() ?: [];
            foreach ($applyList as &$item) {
                $item['true_sexCh'] = TransItem::transGender(Arr::get($item, 'true_sex'));
                $item['statusCh'] = TransItem::transJobApply(Arr::get($item, 'status'));
            }

            $this->response($applyList);
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 审核用户报名兼职
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function checkUsers()
    {
        $applyId = $this->request->post('applyId', 0);
        $jobId = $this->request->post('jobId', 0);
        $status = $this->request->post('pass', 0);
        if ($applyId && $jobId && $status) {
            $result = (new JobOptionService())->auditUserApplyJob([
                'applyId'       => $applyId,
                'jobId'         => $jobId,
                'status'        => $status,
                'message'       => $this->request->post('message', '审核通过!'),
                'auditUserId'       => $this->userId
            ]);
            if ($result) {
                $this->response([
                    'applyId'       => $applyId,
                    'status'        => $status,
                    'statusCh'      => TransItem::transJobApply($status),
                ]);
            }
            $this->response(
                [],
                ApiConstant::JOB_USER_APPLY_CHECK_ERROR,
                ApiConstant::JOB_USER_APPLY_CHECK_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }




    /**
     * 删除兼职 -- 发布人取消该兼职获得
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delJob()
    {
        $jobId = $this->request->post('id', 0);
        $jobInfo = Db::name('jobs')
            ->where('id', $jobId)
            ->where('status', 'IN', [0,1,2])
            ->where('user_id', $this->userId)
            ->where('is_deleted', 0)
            ->find() ?: [];
        if ($jobInfo) {
            try {
                $result = (new JobOptionService())->deleteJob($jobInfo, $this->userId);
                if ($result) {
                    $this->response([
                        'jobId'     => $jobId
                    ]);
                } else {
                    $this->response(
                        [],
                        ApiConstant::API_ERROR,
                        ApiConstant::API_ERROR_STR
                    );
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 结束招聘
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function closeApply()
    {
        $jobId = $this->request->post('id', 0);
        $jobInfo = Db::name('jobs')->where('id', $jobId)
            ->where('user_id', $this->userId)
            ->where('is_deleted', 0)
            ->find() ?: [];
        if ($jobInfo) {
            try {
                $result = (new JobOptionService())->closeApplyJob($jobInfo, $this->userId);
                if ($result) {
                    $this->response([
                        'jobId'     => $jobId
                    ]);
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 完成兼职，结算
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function doneJob()
    {
        $jobId = $this->request->post('id', 0);
        $jobInfo = Db::name('jobs')
            ->where('id', $jobId)
            ->where('user_id', $this->userId)
            ->where('is_deleted', 0)
            ->find() ?: [];
        if ($jobInfo) {
            try {
                $result = (new JobOptionService())->doneJob($jobInfo);
                if ($result) {
                    $this->response([
                        'jobId'     => $jobId
                    ]);
                }
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    ApiConstant::API_ERROR_STR
                );
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 用户取消兼职
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancelJob()
    {
        $jobId = $this->request->post('jobId', 0);
        $applyId = $this->request->post('applyId', 0);
        $message = $this->request->post('message', '');
        $applyInfo = Db::name('jobs_apply')
            ->where('id', $applyId)
            ->where('user_id', $this->userId)
            ->where('job_id', $jobId)
            ->find() ?: [];
        if ($applyInfo) {
            try {
                $result = (new JobOptionService())->cancelApplyJob($applyInfo, $message);
                if ($result) {
                    $this->response([
                        'applyId'   => $applyId,
                        'status'    => 6,
                        'statusCh'  => TransItem::transJobApply(6)
                    ]);
                } else {
                    $this->response(
                        [],
                        ApiConstant::API_ERROR,
                        ApiConstant::API_ERROR_STR
                    );
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 置顶兼职
     */
    public function topJob()
    {
        $jobId = $this->request->post('id', 0);
        if ($jobId) {
            try {
                $result = (new JobOptionService())->setJobTop($jobId, $this->userId);
                if ($result) {
                    $this->response([
                        'jobId'    => $jobId
                    ]);
                } else {
                    $this->response(
                        [],
                        ApiConstant::API_ERROR,
                        ApiConstant::API_ERROR_STR
                    );
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }




    /**
     * 用户收藏的兼职列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function jobCollectList()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 8);

        $jobCollectList = Db::name('user_collect')
            ->where('user_id', $this->userId)
            ->where('type', 1)
            ->order('id DESC')
            ->page($page, $pageSize)
            ->select() ?: [];

        $result = [];
        if ($jobCollectList) {
            $result = (new JobService())->jobList(
                [
                    'jobIdArr'    => array_column($jobCollectList, 'collect_id'),
                ],
                1,
                8
            );
        }

        $this->response($result);
    }



}
